package com.example.dangdangbackend.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;

import com.example.dangdangbackend.config.AlipayConfig;
import com.example.dangdangbackend.entity.Order;
import com.example.dangdangbackend.mapper.ItemMapper;
import com.example.dangdangbackend.mapper.OrderMapper;
import com.example.dangdangbackend.service.PayService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service
@Slf4j
public class PayServiceImpl implements PayService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ItemMapper itemMapper;

    @Override
    public void pay(int orderId) throws Exception{
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert servletRequestAttributes != null;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();

        request.setCharacterEncoding("utf-8");
        assert response != null;
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        alipayRequest.setReturnUrl(AlipayConfig.return_url);

        Order order = orderMapper.getOrderByOrderId(orderId);
        int out_trade_no = order.getOrderId();
        String total_amount = String.valueOf(order.getTotal());
        String subject = "dangdang";
        String body = "buy book";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        /*Pay one = this.getOne(Wrappers.<Pay>lambdaQuery().eq(Pay::getOrderId, orderId));
        if (ObjectUtils.isEmpty(one)){
            Pay pay = new Pay();
            pay.setPayMethod(1);
            pay.setPayStatus(10);
            pay.setOrderId(orderId);
            pay.setComeFrom("ali");
            pay.setReturnUrl("jiaxin");
            pay.setUserId(order.getUserId());
            pay.setCreateTime(LocalDateTime.now());
            pay.setAmount(new BigDecimal(order.getTotal()));
            this.save(pay);
        }*/
        PrintWriter out = response.getWriter();
        out.println(result);
    }

    public void payNotify() throws Exception{
        log.info("执行了notify操作-------------------------------");
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");

        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV2(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }


    }

    public void payReturn() throws Exception{
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");

        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println("接收到的支付宝的反馈参数：");
        for(Map.Entry<String,String> e:params.entrySet()){
            System.out.println(e.getKey()+"="+e.getValue());
        }

        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
       /* String orderId = request.getParameter("out_trade_no");
        System.err.println("orderId = " + orderId);
        Order order = new Order();
        order.setStatus("payed");
        order.setOrderId(orderId);
        orderMapper.updateById(order);
*/


        int orderId = Integer.parseInt(request.getParameter("out_trade_no"));
        System.err.println("orderId = " + orderId);
        Order order = new Order();
        order.setOrderId(orderId);
        orderMapper.updateByOrderId(order);

        log.info("执行update操作---------------------------------------------");
        PrintWriter out = response.getWriter();
        if(signVerified) {
            out.println("<script>window.close()</script>");
        }else {
            out.println("验签失败");
        }

    }
}


